﻿using AiQiuQuan.Sport.Core;
using AiQiuQuan.Sport.WebApi.Repositories;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// 微信回调（除支付退款回调）
    /// </summary>
    public class WxCallbackService : IWxCallbackService
    {
        private readonly IAccessTokenService _accessTokenService;
        private readonly ILogger<WxCallbackService> _logger;
        private readonly IBaseUserRepository _baseUserRepository;

        /// <summary>
        /// ctor
        /// </summary>
        public WxCallbackService(
            IAccessTokenService accessTokenService,
            ILogger<WxCallbackService> logger,
            IBaseUserRepository baseUserRepository)
        {
            _logger = logger;
            _accessTokenService = accessTokenService;
            _baseUserRepository = baseUserRepository;
        }

        /// <summary>
        /// 微信公众号授权回调
        /// </summary>
        /// <param name="code">code</param>
        /// <param name="state">附加参数</param>]
        public async Task<UnaryResult> AuthenticateAsync(string code, string state)
        {
            var webTokenResult = await _accessTokenService.GetWxMpWebAccessTokenAsync(code);
            if (webTokenResult.Code != 0)
            {
                _logger.LogInformation($"微信网页授权失败:{state},{webTokenResult.Msg}");
                return UnaryResult.Faild(webTokenResult.Code, webTokenResult.Msg);
            }

            var userUpdateBuilder = await _baseUserRepository.UpdatePartialAsync();
            await userUpdateBuilder.Set(m => m.U_WxOpenId, webTokenResult.Data.MpOpenId)
                .Set(m => m.UpdateTime, DateTimeOffset.Now)
                .Where(m => m.U_Code == int.Parse(state)).ExecuteAsync();

            return UnaryResult.Succeed();
        }
    }
}